<?php
/**
 * Bootstrap
 * 
 * 作者:  姚刚 (yaogang@the9sense.com)
 * 创建时间: 2011-02-24 00:14:16
 * 修改记录: 
 * 
 * $Id: Bootstrap.php 18 2011-04-17 12:50:07Z coosuu $
 */

class Bootstrap {

    const INTERFACE_WEB = 1;

    const INTERFACE_CLI = 2;

    private static $_instance = null;

    private static $_env = array();

    private static $_benchmark = array();

    public static function &factory($options = array()) {

        if (self::$_instance) {
            return self::$_instance;
        }

        $ifName = 'Web';
        if ($options['interface'] == self::INTERFACE_CLI || php_sapi_name() == 'cli') {
            $ifName = 'Cli';
        }

        require_once ROOT_PATH . '/framework/library/Bootstrap/Abstract.php';
        require_once ROOT_PATH . '/framework/library/Bootstrap/' . $ifName . '.php';

        $className = 'Bootstrap_' . $ifName;
        self::$_instance =& new $className($options);
        return self::$_instance;
    }

    /**
     * setEnv 
     * 
     * @param  mixed $key 
     * @param  mixed $value 
     * @return void
     */
    public static function setEnv($key, $value = null) {

        if (is_array($key)) {
            foreach ($key as $k => $v) {
                self::$_env[$k] = $v;
            }
            return true;
        }

        self::$_env[$key] = $value;
    }

    /**
     * getEnv 
     * 
     * @param  mixed $key 
     * @return void
     */
    public static function getEnv($key = null) {

        if (!$key) {
            return self::$_env;
        }

        if (array_key_exists($key, self::$_env)) {
            return self::$_env[$key];
        }

        return null;
    }

    /**
     * setBenchmark 
     * 
     * @param  mixed $key 
     * @param  mixed $time 
     * @return void
     */
    public static function setBenchmark($key) {

        if (array_key_exists($key, self::$_benchmark)) {
            $key .= '.ended';
        }

        self::$_benchmark[$key] = microtime(true);
    }

    /**
     * getBenchmark 
     * 
     * @param  mixed $key 
     * @return void
     */
    public static function getBenchmark($key) {

        if (!array_key_exists($key, self::$_benchmark)) {
            return 0;
        }

        $endtime = microtime(true);
        if (array_key_exists($key . '.ended', self::$_benchmark)) {
            $endtime = self::$_benchmark[$key . '.ended'];
        }

        return $endtime - self::$_benchmark[$key];
    }
}
